package cn.cdnsu.auth.interceptors;

import cn.cdnsu.auth.annotation.NsuPermission;
import cn.cdnsu.base.util.LoginContext;
import cn.cdnsu.org.domain.Employee;
import cn.cdnsu.org.service.IEmployeeServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private IEmployeeServiceI service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("tokenYa");
        System.out.println(token);
        if (StringUtils.isEmpty(token)){
            System.out.println("没有传入token");
            response.getWriter().print("{\"success\":false,\"msg\":\"NoLogin\"}");
            return false;
        }
       Employee user = (Employee) LoginContext.loginMap.get(token);
        if (Objects.isNull(user)){
            System.out.println("token取值错误");
            response.getWriter().print("{\"success\":false,\"msg\":\"NoLogin\"}");
            return false;
        }


        //对于url路径的权限控制
        //1.判断用户访问的资源是否需要权限
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        NsuPermission methodAnnotation = handlerMethod.getMethod().getAnnotation(NsuPermission.class);
        if (Objects.nonNull(methodAnnotation)){
        //2.如果需要权限，判断用户是否有权限.
        // 2.1通过角色拿到用户的权限,Object就是map里放入的用户,将它强转成Employee型
        List<String> list=service.queryPermissionByUserId(user.getId());
        //2.2拿到资源的权限
            Method method = handlerMethod.getMethod();
            String mP=method.getDeclaringClass().getSimpleName()+":"+method.getName();
            //3.比较用户的权限和资源的权限，如果比对上就放行，否则拦截
            if (!list.contains(mP)){
                response.getWriter().print("{\"success\":false,\"msg\":\"NoPermission\"}");

                return false;
            }
        }
        return true;
    }
}
